class AreasController < ApplicationController
  # for xhr, return areas list
  def list
    list_result
  end
  
  def list_for_user
    list_result
  end
  
  def list_for_admin
    list_result
  end
  
  def new
    @area = Area.new()
    # pass pid to view, and use in create method
    @parent_id = params[:pid]
    render :layout => false
  end
  
  def create
    if params[:pid].to_i == 0
      # pid=0 means create a root item
      @area = Area.create(params[:area])
    else
      # pid is the parent of the item you want to create
      @parent = Area.find(params[:pid])
      @area = Area.create(params[:area])
      @area.move_to_child_of @parent
    end
  end
  
  
  def edit
    @area = Area.find(params[:id])
    render :layout => false
  end
  
  def update
    #return false if params[:title].blank?
    @area = Area.find(params[:id])
    @area.update_attributes!(params[:area])
  end
  
  def destroy
    @area = Area.find(params[:id])
    area_ids = [@area.id]
    area_ids << @area.all_children.collect{|a| a.id}
    logger.info("----AREA IDs: #{area_ids.flatten}")
    Area.transaction do
      @area.destroy
      School.update_all(["is_hidden=?, area_id=?", true, @area.parent_id], "area_id in (#{area_ids.flatten.join(',')})")
    end
  end
  
  private
  def list_result
    if params[:id].blank? || params[:id].to_i == 0
      @areas = Area.roots
    else
      @parent = Area.find(params[:id])
      @areas = @parent.children
    end
  end
end
